package org.geektimes.projects.user.web.controller;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.service.UserService;
import org.geektimes.web.mvc.controller.PageController;
import org.geektimes.web.mvc.controller.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.ws.rs.Path;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Path("/user")
public class UserController implements PageController {

    @Resource(name = "bean/UserService")
    private UserService userService;

    @Resource(name = "bean/Validator")
    private Validator validator;

    @Path("/register")
    public void register(HttpServletRequest request, HttpServletResponse response) {
        User user = readEntity(request,User.class);
        Set<ConstraintViolation<User>> violations = validator.validate(user);
        List<String> messages = violations.stream().map(violation -> violation.getMessage()).collect(Collectors.toList());
        if (messages.size() > 0) {
            request.setAttribute("message",StringUtils.join(messages,","));
        } else {
           userService.register(user);
           request.setAttribute("user",user);
        }
    }

    private <T> T readEntity(HttpServletRequest request, Class<T> clazz) {
        try {
            BufferedReader reader = request.getReader();
            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            return JSON.parseObject(sb.toString(),clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        return null;
    }
}
